package com.gulimall.product.exception;

import com.common.exception.BizCodeEnume;
import com.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mayifan
 * @version 1.0
 * @date 2024-08-26 16:49
 */
//集中处理所有异常

@Slf4j
@RestControllerAdvice(basePackages = "com.gulimall.product.controller")
public class GulimallExceptionControllerAdivice {


//    告诉SPringMVC这个方法能处理什么异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
            Map<String,String> errormap = new HashMap<>();
//            获取校验的结果
            result.getFieldErrors().forEach((fieldError)->{
//                获取错误提示
                String message = fieldError.getDefaultMessage();
//                获取错误的属性名字
                String field = fieldError.getField();
                errormap.put(field,message);
            });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errormap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){

        return R.error(BizCodeEnume.UNKONW_EXCEPTION.getCode(),BizCodeEnume.UNKONW_EXCEPTION.getMsg());
    }
}
